<template>
  <div>
    <el-dialog
      title="组织机构"
      :visible.sync="dialogVisible"
      @close="closeOpen"
      :modal="true"
      :appendToBody="true"
      width="500px"
      v-dialog-drag
      :close-on-click-modal="false"
      :top="scrollTop"
    >
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText"
        style="margin-bottom: 10px"
      >
      </el-input>
      <el-tree
        :data="dept"
        :check-strictly="true"
        show-checkbox
        check-on-click-node
        :expand-on-click-node="false"
        accordion
        node-key="id"
        ref="tree"
        highlight-current
        :default-checked-keys="checkedkey"
        :filter-node-method="filterNode"
        :default-expanded-keys="id"
        @check-change="parentModules"
        :props="defaultProps"
        v-if="dialogVisible"
        v-loading="loading"
        style="max-height: calc(100vh - 380px);overflow: auto"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button @click="dialogVisible= false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import request from '@/utils/request';
  import { foreachTreeData } from '@/utils/tree'
  export default {
    name: "index",
    data(){
      return {
        filterText:'',
        id: [],
        dept:[],
        defaultProps: {
          children: 'children',
          label: 'label',
          disabled: (data, node) => {
            if (this.nodeDisabledCallback && Object.prototype.toString.call(this.nodeDisabledCallback) === '[object Function]') {
              return this.nodeDisabledCallback(data, node)
            }
            return false
          }
        },
        // uniqueValue:'',
        checkedkey:[],
        loading:true,
        scrollTop: null ,

      }
    },
    props: {
      'visibles':{
        type:Boolean,
        default:false
      },
      'branchcode':{
        type:[String,Number,Array],
        default:''
      },
      // 判断哪些节点可选（回调函数判断方式，回调返回true和false，为true，可选，为false不可选）
      // 如果为空等，则认为是全部可选
      nodeDisabledCallback: {
        type: Function
      },
      // 是否回填默认值
      'isDefaultValue': {
        type:Boolean,
        default:true
      },
      // 单选/多选，默认组织筛选时单选
      'isSingleCheck': {
        type: Boolean,
        default: true
      }
    },
    computed: {
      dialogVisible: {
        set(val) {
          this.$emit("update:visibles", val)
        },
        get(){
          return this.visibles
        }
      }
    },
   created() {

    },
    watch:{
      'dialogVisible':function(){        
        // 默认选中值处理
        const dataType = Object.prototype.toString.call(this.branchcode)
        if (dataType === '[object Number]') {
          this.id = this.branchcode ? [this.branchcode] : [];
        } else if (dataType === '[object String]') {
          this.id = this.branchcode.split(',');
        }

        if (this.dialogVisible === false){
          this.filterText = '';
        }else{
          this.$nextTick(() => {
            console.log("是否填充默认值：",this.isDefaultValue);
            if(!this.isDefaultValue) return;
            if (this.id?.length) {
              this.$refs.tree.setCheckedKeys(this.id);
              this.$refs.tree.setCurrentKey(this.id[0]);
            }
          });
          this.getDept();
        }
      },
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    methods: {
      closeOpen() {
      },
      handleSave() {
        var ids = this.$refs.tree.getCheckedKeys();
        var arr = [];

        for (let i = 0; i < ids.length; i++) {
          const id = ids[i];
          let obj = this.$refs.tree.getNode(id).data;
          arr.push(obj);
          if (this.isSingleCheck && i === 0) {
            break
          }
        }

        this.$emit('closeDialog',arr)

        this.dialogVisible = false;
      },
      //获取领料单数据
       getDept() {
        this.loading = true;
        var that = this;
        request({
          url: '/system/dept/treeselect',
          method: 'get'
        }).then(res=>{
          const data = res.data
          // 把节点的所有父节点id都缓存在节点的parentsId中
          foreachTreeData(data, (node, parent) => {
            if (parent) {
              node.parentsId = [parent.id, ...parent.parentsId]
            } else {
              node.parentsId = []
            }
          })
          that.dept = data;

          that.loading = false;
        }).catch(err=>{
          that.$message.error('数据获取失败！');
          that.loading = false;
        })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      parentModules(data,checkbox,node){
        if (!this.isSingleCheck) {
          return
        }
        if(checkbox){
          // 后端返回的node-key不是id，是moduldCode
          this.$refs.tree.setCheckedKeys([data.id]);
          this.$refs.tree.setCurrentKey(data.id);
          // this.uniqueValue =  this.$refs.tree.getCheckedKeys();
        }else{
          // this.uniqueValue =  this.$refs.tree.getCheckedKeys();
          // if(this.uniqueValue.length == 0){
          //   this.uniqueValue = ''
          // }
        }
      },
    },
    mounted() {
      this.utils.mounteds(this);
    },
    destroyed() {
      this.utils.destroyeds(this);
    },
  }
</script>

<style scoped>

</style>
